<template>
  <n-form :model="form" :rules="rules" ref="formRef" size="large">
    <n-form-item path="email">
      <n-input placeholder="邮箱" v-model:value="form.email"/>
    </n-form-item>
    <n-form-item path="code">
      <n-input-group>
        <n-input placeholder="验证码" v-model:value="form.code"/>

        <n-button :loading="codeLoading" :disabled="count!==0" @click="handleGetCode" type="primary" ghost>
          <div v-if="count===0">获取验证码</div>
          <div v-else>{{ count }}秒后重新获取</div>
        </n-button>
      </n-input-group>
    </n-form-item>
    <n-form-item  path="password">
      <n-input type="password" placeholder="输入密码" v-model:value="form.password"/>
    </n-form-item>
    <n-form-item  path="againPassword">
      <n-input type="password" :disabled="!form.password" placeholder="重复密码"
               v-model:value="form.againPassword" @keydown.enter.prevent="handleForget"/>
    </n-form-item>
  </n-form>
  <n-button type="success"
            size="large"
            circle
            :loading="loading"
            class="bg-green-600 dark:bg-green-400"
            block @click="handleForget">
    确认重置
  </n-button>
</template>

<script setup lang="ts">
import {onMounted, ref} from "vue";
import { encrypt} from "@/utils";
import {useDebounceFn} from '@vueuse/core'
import {FormItemRule} from "naive-ui";
import {useAppStore} from "@/store/module/app";
import dayjs from "@/utils/dayjs";
import api from "@/api";


const appStore = useAppStore()

const count = ref(0)


const loading = ref(false)
const codeLoading = ref(false)
const form = ref<IForgetForm>({
  email: '',
  code: '',
  password: '',
  againPassword: '',
})
const formRef = ref()
const rules = ref({
  email: [{
    key: 'a',
    required: true,
    message: '请输入邮箱',
    trigger: ['input'],
  }, {
    key: 'b',
    message: '邮箱输入有误',
    validator: (_: FormItemRule, value: string) => {
      return /^[\w-.]+@([\w-]+\.)+[\w-]{2,4}$/.test(value)
    }
  }],
  code: [{
    required: true,
    message: '请输入验证码',
    trigger: ['input'],

  }],
  password: [{
    required: true,
    message: '请输入密码',
    trigger: ['input']
  }, {
    validator: validatePasswordStartWith,
    message: '两次密码输入不一致',
    trigger: 'input'
  }],
  againPassword: [{
    required: true,
    message: '请再次输入密码',
    trigger: ['input']
  }, {
    validator: validatePasswordSame,
    message: '两次密码输入不一致',
    trigger: 'input'
  }]
})
onMounted(() => {
  count.value = 60 - (dayjs().unix() - appStore.emailGetCodeTime)
  if (count.value > 0) {
    countDown()
  } else {
    count.value = 0
  }
})

const handleGetCode = () => {
  formRef.value.validate((errors: any) => {
    if (!errors) {
      codeLoading.value = true
      api.mail.code({email: form.value.email}).then((res: any) => {
        if (res.data.code === 0) {
          window.$message.success(res.data.msg)
          appStore.startEmailCode()
          count.value = 60
          countDown()
        }
      }).finally(() => {
        codeLoading.value = false
      })
    }
  }, (rule: any) => {
    return rule?.key === 'a' || rule?.key === 'b'
  })

}

const countDown = () => {
  let timer = setInterval(() => {
    count.value--
    if (count.value <= 0) {
      clearInterval(timer)
      count.value = 0
    }
  }, 1000)
}
const handleForget = useDebounceFn(() => {
  formRef.value.validate((error: any) => {
    if (!error) {
      loading.value = true
      api.user.forget({
        email:form.value.email,
        code:form.value.code,
        password: encrypt(form.value.password)
      }).then((res: any) => {
        if (res.data.code === 0) {
          window.$message.success(res.data.msg)
        }
      }).finally(() => {
        loading.value = false
      })
    }
  })
}, 200)


function validatePasswordStartWith(
    rule: FormItemRule,
    value: string
): boolean {
  console.log(rule)
  return (
      !!form.value.password &&
      form.value.password.startsWith(value) &&
      form.value.password.length >= value.length
  )
}

function validatePasswordSame(rule: FormItemRule, value: string): boolean {
  console.log(rule)
  return value === form.value.password
}

</script>

<style scoped>

</style>
